#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h> 
#include <netinet/in.h>
#include <linux/sockios.h>
#include <linux/wireless.h>


#include "util.h"

#define  BLOOM_FILTER_STR_SIZE  (sizeof(bloom_filter_t) * 2 + 1)

static struct sockaddr_in *get_if_info(char *ifname, int type);

const char *ip_to_string(u_int32_t addr)
{
    struct in_addr a;
    static char buf[16 * 4];
    static int index = 0;
    char *str;

    a.s_addr = htonl(addr);
    strcpy(&buf[index], inet_ntoa(a));
    str = &buf[index];
    index += 16;
    index %= 64;
    return str;
}

const char * bloom_filter_to_string(bloom_filter_t filter) { 
	static char buf[BLOOM_FILTER_STR_SIZE * 4]; 
	static int index = 0; 
	char * str; 
	
	str = buf + index * BLOOM_FILTER_STR_SIZE;
	bloom_filter_to_hex_string(filter, str, BLOOM_FILTER_STR_SIZE); 
	index = (index + 1) % 4; 
	return str; 		
}

u_int32_t get_local_ip_address()
{ 
	struct sockaddr_in * ina = get_if_info("eth1", SIOCGIFADDR);	
	if (ina == NULL) { 
		fprintf(stderr, "Error: cannot get the local ip address\n"); 
		exit(-1); 
	}
	return ntohl(ina->sin_addr.s_addr); 
}

static struct sockaddr_in *get_if_info(char *ifname, int type)
{
    int skfd;
    struct sockaddr_in *ina;
    struct ifreq ifr;

    /* Get address of interface... */
    skfd = socket(AF_INET, SOCK_DGRAM, 0);

    strcpy(ifr.ifr_name, ifname);
    if (ioctl(skfd, type, &ifr) < 0) {
    	perror("Error in ioctl"); 
		close(skfd);
		return NULL;
    } else {
		ina = (struct sockaddr_in *) &ifr.ifr_addr;
		close(skfd);
		return ina;
    }
}
